import request from "@/utils/request";
import type {
  DistributionDashboardData,
  DistributionOverviewMetrics,
  BrandPerformanceData,
  CategoryAnalysisData,
  OperationModeAnalysis,
  BrandRankingData,
  TrendDataPoint,
  DistributionData,
  DistributionRealTimeData,
  DateRangeQuery,
  BrandQuery,
  PageResult,
  AnalysisQuery
} from '@/types/distribution';

const DISTRIBUTION_BASE_URL = "/api/v1/distribution/dashboard";

export const distributionApi = {
  /**
   * 获取经销看板完整数据
   */
  getDashboardData(params?: DateRangeQuery) {
    return request<any, DistributionDashboardData>({
      url: `${DISTRIBUTION_BASE_URL}/all`,
      method: "get",
      params,
    });
  },

  /**
   * 获取经销概览指标
   */
  getOverviewMetrics(params?: DateRangeQuery) {
    return request<any, DistributionOverviewMetrics>({
      url: `${DISTRIBUTION_BASE_URL}/overview`,
      method: "get",
      params,
    });
  },

  /**
   * 获取品牌表现数据列表（分页）
   */
  getBrandPerformanceList(params?: BrandQuery) {
    return request<any, PageResult<BrandPerformanceData>>({
      url: `${DISTRIBUTION_BASE_URL}/brand-performance`,
      method: "get",
      params,
    });
  },

  /**
   * 获取品牌详细信息
   */
  getBrandDetail(brandName: string, params?: DateRangeQuery) {
    return request<any, BrandPerformanceData>({
      url: `${DISTRIBUTION_BASE_URL}/brand-detail/${encodeURIComponent(brandName)}`,
      method: "get",
      params,
    });
  },

  /**
   * 获取类目分析数据
   */
  getCategoryAnalysis(params?: DateRangeQuery & { categoryLevel?: 1 | 2 | 3 }) {
    return request<any, CategoryAnalysisData[]>({
      url: `${DISTRIBUTION_BASE_URL}/category-analysis`,
      method: "get",
      params,
    });
  },

  /**
   * 获取经营模式分析
   */
  getOperationModeAnalysis(params?: DateRangeQuery) {
    return request<any, { data: OperationModeAnalysis[] }>({
      url: `${DISTRIBUTION_BASE_URL}/operation-mode-analysis`,
      method: "get",
      params,
    });
  },

  /**
   * 获取品牌排行榜
   */
  getBrandRanking(params?: DateRangeQuery & { limit?: number; sortBy?: string }) {
    return request<any, { data: BrandRankingData[] }>({
      url: `${DISTRIBUTION_BASE_URL}/brand-ranking`,
      method: "get",
      params,
    });
  },

  /**
   * 获取成交金额趋势
   */
  getAmountTrend(params?: DateRangeQuery & { granularity?: 'day' | 'week' | 'month' }) {
    return request<any, { data: TrendDataPoint[] }>({
      url: `${DISTRIBUTION_BASE_URL}/amount-trend`,
      method: "get",
      params,
    });
  },

  /**
   * 获取品牌数量趋势
   */
  getBrandCountTrend(params?: DateRangeQuery & { granularity?: 'day' | 'week' | 'month' }) {
    return request<any, { data: TrendDataPoint[] }>({
      url: `${DISTRIBUTION_BASE_URL}/brand-count-trend`,
      method: "get",
      params,
    });
  },

  /**
   * 获取转化率趋势
   */
  getConversionTrend(params?: DateRangeQuery & { granularity?: 'day' | 'week' | 'month' }) {
    return request<any, { data: TrendDataPoint[] }>({
      url: `${DISTRIBUTION_BASE_URL}/conversion-trend`,
      method: "get",
      params,
    });
  },

  /**
   * 获取类目分布数据
   */
  getCategoryDistribution(params?: DateRangeQuery & { categoryLevel?: 1 | 2 | 3 }) {
    return request<any, DistributionData[]>({
      url: `${DISTRIBUTION_BASE_URL}/category-distribution`,
      method: "get",
      params,
    });
  },

  /**
   * 获取经营模式分布
   */
  getOperationModeDistribution(params?: DateRangeQuery) {
    return request<any, DistributionData[]>({
      url: `${DISTRIBUTION_BASE_URL}/operation-mode-distribution`,
      method: "get",
      params,
    });
  },

  /**
   * 获取实时数据
   */
  getRealTimeData() {
    return request<any, DistributionRealTimeData>({
      url: `${DISTRIBUTION_BASE_URL}/realtime`,
      method: "get",
    });
  },

  /**
   * 导出品牌表现数据
   */
  async exportBrandPerformance(params?: BrandQuery): Promise<Blob> {
    const response = await request<any, any>({
      url: `${DISTRIBUTION_BASE_URL}/export/brand-performance`,
      method: "post",
      data: params,
      responseType: 'blob',
    });
    
    // 如果响应是AxiosResponse对象，则提取data
    if (response && typeof response === 'object' && 'data' in response) {
      return response.data as Blob;
    }
    
    // 否则直接返回（可能已经是Blob）
    return response as Blob;
  },

  /**
   * 获取统计分析数据
   */
  getAnalysisData(params: AnalysisQuery) {
    return request<any, any>({
      url: `${DISTRIBUTION_BASE_URL}/analysis`,
      method: "get",
      params,
    });
  },

  /**
   * 刷新经销数据
   */
  refreshData() {
    return request<any, string>({
      url: `${DISTRIBUTION_BASE_URL}/refresh`,
      method: "post",
    });
  },

  /**
   * 获取品牌列表（用于下拉选择）
   */
  getBrandOptions() {
    return request<any, string[]>({
      url: `${DISTRIBUTION_BASE_URL}/brand-options`,
      method: "get",
    });
  },

  /**
   * 获取类目列表（用于下拉选择）
   */
  getCategoryOptions() {
    return request<any, string[]>({
      url: `${DISTRIBUTION_BASE_URL}/category-options`,
      method: "get",
    });
  },

  /**
   * 获取经营模式列表（用于下拉选择）
   */
  getOperationModeOptions() {
    return request<any, string[]>({
      url: `${DISTRIBUTION_BASE_URL}/operation-mode-options`,
      method: "get",
    });
  },

  /**
   * 检查API健康状态
   */
  async checkApiHealth(): Promise<boolean> {
    try {
      await request({
        url: `${DISTRIBUTION_BASE_URL}/health`,
        method: "get",
        timeout: 5000,
      });
      return true;
    } catch (error) {
      console.error('经销API健康检查失败:', error);
      return false;
    }
  },
};

export default distributionApi; 